package com.wzy.service.reposirory.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.common.base.redis.RedisUtil;
import com.wzy.common.base.result.R;
import com.wzy.common.base.result.ResultCodeEnum;
import com.wzy.service.reposirory.dto.UserGlobalWord;
import com.wzy.service.reposirory.entity.GlobalWord;
import com.wzy.service.reposirory.entity.UserSentence;
import com.wzy.service.reposirory.entity.UserWord;
import com.wzy.service.reposirory.mapper.GlobalWordMapper;
import com.wzy.service.reposirory.mapper.UserSentenceMapper;
import com.wzy.service.reposirory.mapper.UserWordMapper;
import com.wzy.service.reposirory.service.UserWordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuzhengyu
 * @since 2021-03-13
 */
@Service
public class UserWordServiceImpl extends ServiceImpl<UserWordMapper, UserWord> implements UserWordService {

    // 日志
    private static Logger logger = LoggerFactory.getLogger(UserWordServiceImpl.class);



    // code
    private static final String OK = "0";

    private static final Integer INSERT_SUCCESS = 1;
    private static final String REDIS_KEY = "every-day-word-";

    @Autowired
    UserWordMapper userWordMapper;
    @Autowired
    UserSentenceMapper userSentenceMapper;
    @Autowired
    GlobalWordMapper globalWordMapper;


    @Autowired
    RedisUtil redisUtil;

    @Override
    public R getUserWords(String uid) {
        if (uid == null) {
            return R.error(ResultCodeEnum.PARAM_ERROR);
        }
        List<UserWord> words = userWordMapper.selectList(Wrappers.<UserWord>lambdaQuery().eq(UserWord::getUid, uid));
        return R.ok().data("words", words);
    }

    @Override
    public R articleBreak(String article, Long uid) {
        // 分解为句子 查找翻译 存入数据库
        List<UserSentence> sentences = article2Sentence(article,uid);
        List<UserWord> words = new ArrayList<>();
        // 分解为单词 查找翻译 存入数据库
        sentences.forEach(s -> {
            List<UserWord> word = sentence2Word(s.getSentence(), uid, s.getId());
            words.addAll(word);
        });
        return R.ok().data("words",words).data("sentences", sentences);
    }

    @Override
    public List<UserWord> generateEverDayWord(String uid, String number, String ratio) {
        return null;
    }

    //@Override
    //public List<UserWord> generateEverDayWord(String uid, String number, String ratio) {
    //    // 计算出新旧单词数量
    //    int numberInt = Integer.parseInt(number);
    //    double ratioDouble = Double.parseDouble(ratio);
    //    int newWordNum = (int)Math.ceil(numberInt * ratioDouble);
    //
    //    // 取新单词
    //    // 新单词定义 用户测试次数 <= 10次的 都是新单词
    //    List<UserWord> allWords = new ArrayList<>();
    //    List<UserWord> newUserWords = userWordMapper.selectList(Wrappers.<UserWord>lambdaQuery().le(UserWord::getTestNumber, "10").eq(UserWord::getUid,uid).orderByAsc(UserWord::getTestNumber).last("limit 0 ,"+ newWordNum));
    //    if(newUserWords != null) {
    //        allWords.addAll(newUserWords);
    //    }
    //
    //    int oldWordNum = numberInt - allWords.size();
    //
    //    List<UserWord> oldUserWords = userWordMapper.selectList(Wrappers
    //            .<UserWord>lambdaQuery()
    //            .gt(UserWord::getTestNumber, "10")
    //            .orderByAsc(UserWord::getLevel)
    //            .last("limit 0 ," + oldWordNum)
    //    );
    //    if (oldUserWords != null) {
    //        allWords.addAll(oldUserWords);
    //    }
    //    // 新旧单词加起来都不够用 就以单词等级作为排序, 然后获取最新的单词
    //    if (allWords.size() < numberInt) {
    //        int i = numberInt - allWords.size();
    //        List<UserWord> l = userWordMapper.selectList(Wrappers.<UserWord>lambdaQuery().le(UserWord::getTestNumber, "10").eq(UserWord::getUid,uid).orderByAsc(UserWord::getTestNumber).last("limit "+ newWordNum + "," + i ));
    //        allWords.addAll(l);
    //    }
    //    return allWords;
    //}

    @Override
    public R wordNumberUpdate(String everyDayWords, String uid) {
        //String str = JacksonUtil.clazz2String(everyDayWords);
        redisUtil.set(REDIS_KEY+uid, everyDayWords);
        return R.ok();
    }

    @Override
    public R wordUpdate(String id, String uid, boolean isPass) {
        if (isPass) {
            userWordMapper.update(null, Wrappers.<UserWord>lambdaUpdate().eq(UserWord::getId, id).setSql("test_number = test_number+1, pass_number = pass_number+1, level = (pass_number+1) /(test_number+1) "));
        } else {
            userWordMapper.update(null, Wrappers.<UserWord>lambdaUpdate().eq(UserWord::getId, id).setSql("test_number = test_number+1, level = pass_number /(test_number+1))" ));
        }
        return R.ok();
    }

    @Override
    public R currentWordNumber(String uid) {

        return null;
    }

    @Override
    public List<UserGlobalWord> getUserGlobalWordBySid(String sid, String uid) {
        return userWordMapper.getUserGlobalWordBySid(sid, uid);
    }


    private List<String> breakToSentence(String article) {
        // 正则表达式分割\过滤\添加.
        return Arrays.stream(article.split("(\\.|\\!|\\?|。|！|？|\\.{6})"))
                .filter(t -> t!=null && !t.equals(""))
                .map(String::trim)
                .map(t -> t+".")
                .collect(Collectors.toList());
    }

    private List<String> breakToWord(String sentence) {
        StringTokenizer st = new StringTokenizer(sentence," ,?.;!:\"\"\n#");
        List<String> wordList = new ArrayList<>();
        while (st.hasMoreElements()) {
            wordList.add(st.nextToken().toLowerCase());
        }
        return wordList.stream()
                .filter(t -> t!=null && !t.equals(""))
                .map(String::trim)
                .distinct() // 去重
                .collect(Collectors.toList());
    }

    private List<UserSentence> article2Sentence(String article, Long uid) {
        //// 分解为句子
        //List<String> sentences = breakToSentence(article);
        //// 创建要返回值的UserSentence
        //List<UserSentence> userSentences = new ArrayList<>();
        //sentences.forEach(s -> {
        //    // 创建Sentence
        //    UserSentence sentence = new UserSentence();
        //    // 对这个句子进行翻译
        //    try {
        //        String chinese = translateSentence(s);
        //        sentence.setTranslate(chinese);
        //    } catch (Exception e) {
        //        e.printStackTrace();
        //    }
        //    sentence.setUid(uid);
        //    sentence.setGmtCreate(new Date());
        //    sentence.setGmtModified(new Date());
        //    sentence.setSentence(s);
        //    if (userSentenceMapper.insert(sentence) != INSERT_SUCCESS) {
        //        logger.error("句子插入失败,句子为:" + s);
        //    }
        //    userSentences.add(sentence);
        //});
        //return userSentences;
        return null;
    }



    private List<UserWord> sentence2Word(String sentence, Long uid, Long sid) {
        // 分解为单词
        //List<String> words = breakToWord(sentence);
        //List<UserWord> userWords = new ArrayList<>();
        //// 挨个翻译,并且存入数据库中
        //words.forEach(s -> {
        //    UserWord userWord;
        //    GlobalWord globalWord = new GlobalWord();
        //    try {
        //        // 从global_word中查询,看能否找到要查询的单词
        //        globalWord = globalWordMapper.selectOne(Wrappers.<GlobalWord>lambdaQuery().eq(GlobalWord::getSpell, s));
        //        if (globalWordMapper.selectOne(Wrappers.<GlobalWord>lambdaQuery().eq(GlobalWord::getSpell, s)) == null) {
        //            // 没有找到要查询的单词,进行查询
        //            Map<String, String> map = translateWord(s);
        //            if (map == null) {
        //                return;
        //            }
        //            globalWord = createGlobalWord(map, s);
        //            // 插入到数据库
        //            if(globalWordMapper.insert(globalWord) == 0) {
        //                logger.error("数据库插入失败");
        //            }
        //        }
        //    } catch (Exception e) {
        //        e.printStackTrace();
        //    }
        //    userWord = userWordMapper.selectOne(Wrappers.<UserWord>lambdaQuery().eq(UserWord::getUid, uid).eq(UserWord::getWord,s));
        //
        //    if (userWord == null) {
        //        userWord = createUserWord(globalWord, s, sid, uid);
        //        if (userWordMapper.insert(userWord) != INSERT_SUCCESS) {
        //            logger.error("单词插入失败,单词为:" + s);
        //        }
        //    }
        //    userWord.setSid(sid);
        //    userWords.add(userWord);
        //
        //});
        //return userWords;
        return null;
    }

    private UserWord createUserWord(GlobalWord globalWord, String s, Long sid, Long uid) {
        //UserWord userWord = new UserWord();
        //userWord.setWid(globalWord.getId());
        //userWord.setTranslate(globalWord.getExplains());
        //userWord.setWord(s);
        //userWord.setStatus("未入库");
        //userWord.setPassNumber(0);
        //userWord.setTestNumber(0);
        //userWord.setLevel(new BigDecimal(0));
        //userWord.setSid(sid);
        //userWord.setUid(uid);
        //userWord.setGmtCreate(new Date());
        //userWord.setGmtModified(new Date());
        //return userWord;
        return null;
    }

    private GlobalWord createGlobalWord(Map<String,String> map, String s) {
        GlobalWord globalWord = new GlobalWord();
        globalWord.setLevel(map.get("level"));
        globalWord.setExplains(map.get("explains"));
        globalWord.setSpell(s);
        globalWord.setUkPhonetic(map.get("ukPhonetic"));
        globalWord.setUsPhonetic(map.get("usPhonetic"));
        globalWord.setUsSpeech(map.get("ukSpeech"));
        globalWord.setUkSpeech(map.get("ukSpeech"));
        globalWord.setGmtCreate(new Date());
        globalWord.setGmtModified(new Date());
        return globalWord;
    }
    public static void main(String[] args) throws Exception {
        System.out.println(new UserWordServiceImpl().breakToWord("what's don't here are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do."));
    }

}
